
#include <testpackage.h>
#include "package.h"
#include "judge_file.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

jstatus_t config_parse(struct package *, char *, size_t);

struct package *package_new() {
	struct package *p = (struct package *)malloc(sizeof(struct package));

	if (p == NULL) 
		return NULL;
	memset(p, 0, sizeof(struct package));
	p->fs.vtable.open = judge_file_open;
	p->fs.vtable.close = judge_file_close;
	p->fs.vtable.read = judge_file_read;
	p->fs.vtable.find = judge_file_find;
	return p;
}

void package_delete(struct package *p) {
	list_free(&p->testcase_list);
	list_free(&p->spj_key_list);
	if (p->temp_buffer != NULL) {
		free(p->temp_buffer);
		p->temp_buffer = NULL;
	}
	if (p->config_file != NULL) {
		zip_fclose(p->config_file);
		p->config_file = NULL;
	}
	if (p->zip != NULL) {
		zip_close(p->zip);
		p->zip = NULL;
	}
	free(p);
}

jstatus_t package_assign(struct package *package, const char *file_path) {
	int zep;
	struct zip_stat zs;
	char *config_data;
	size_t config_size;
	jstatus_t st;

	package->zip = zip_open(file_path, ZIP_FL_NOCASE, &zep);
	if (package->zip == NULL) 
		return JSTATUS_ZIP_ERROR;
	package->config_file = zip_fopen(package->zip, "config.txt", ZIP_FL_NOCASE);
	if (package->config_file == NULL)
		return JSTATUS_ZIP_ERROR;
	zip_stat(package->zip, "config.txt", ZIP_FL_NOCASE, &zs);
	config_size = (size_t)zs.size;
	config_data = (char *)malloc(config_size + 1);
	if (config_data == NULL)
		return JSTATUS_BAD_ALLOC;
	package->temp_buffer = (char *)malloc(config_size + 1);
	if (package->temp_buffer == NULL) {
		free(config_data);
		return JSTATUS_BAD_ALLOC;
	}
	zip_fread(package->config_file, config_data, config_size);
	config_data[config_size] = 0;
	st = config_parse(package, config_data, config_size);
	free(config_data); 
	return st;
}
